package com.example.demo.web.servlet;


import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;

/**
 * 
 * <p>@author Henry.Y</p>
 *
 * <p>2019-07-27</p>
 */
//@WebServlet(name="loginServlet",urlPatterns="/login")
public class LoginServlet extends HttpServlet{

	/**
	 * 
	 */
	
	private static final long serialVersionUID= -4038848689973112336L; 

	protected void doGet(HttpServletRequest request,HttpServletResponse response)throws ServletException,IOException{
		request.getRequestDispatcher("WEB-INF/jsp/login.jsp").forward(request,response);
	}
	
	protected void doPost(HttpServletRequest request,HttpServletResponse response)throws ServletException,IOException{
		String error=null;
		String username= request.getParameter("username");
		String password= request.getParameter("password");
		Subject subject= SecurityUtils.getSubject();
		UsernamePasswordToken token= new UsernamePasswordToken(username,password);
		token.setRememberMe(true);
		try{
			subject.login(token);
		}catch(UnknownAccountException ukae){
			error= "用户名密码错误。";
		}catch(IncorrectCredentialsException icce){
			error= "用户名密码错误";
		}catch(AuthenticationException ae){
			error= "其他错误".concat(ae.getMessage());
		}
		if(null!=error){     //登陆失败,返回登陆页面
			request.setAttribute("error", error);
			request.getRequestDispatcher("WEB-INF/jsp/login.jsp").forward(request,response);
		}else{               //登陆成功                                                           
			request.getRequestDispatcher("WEB-INF/jsp/loginSuccess.jsp").forward(request, response);;
		}
	}
}
